package com.tgjs.sphoto.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tgjs.sphoto.adapter.PhotoAdapter;
import com.tgjs.sphoto.entity.PhotosDTO;
import com.tgjs.sphoto.request.Api;
import com.tgjs.sphoto.utils.FileUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

public class MainActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, OnLoadMoreListener, OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener {

	@BindView(R.id.recycleView)
	RecyclerView recycleView;
	@BindView(R.id.smartRefresh)
	SmartRefreshLayout smartRefresh;
	private PhotoAdapter adapter;
	private int pages;
	private static long lastBackTime = 0;
	private final int BACK_INTERVAL = 1000;
	private RxPermissions rxPermissions;

	@Override
	protected int getContentView() {
		return R.layout.activity_main;
	}

	@Override
	protected void initViews() {
		mApi = new Api(handler, MainActivity.this);
		rxPermissions = new RxPermissions(this);
		smartRefresh.setRefreshFooter(new ClassicsFooter(this));
		smartRefresh.setRefreshHeader(new ClassicsHeader(this));
		smartRefresh.setOnLoadMoreListener(this);
		smartRefresh.setOnRefreshListener(this);
		LinearLayoutManager layoutManager = new LinearLayoutManager(this);
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		recycleView.setLayoutManager(layoutManager);
		adapter = new PhotoAdapter(null);
		pages = 1;
		getPhotos(pages);
		setPermissions();
		recycleView.setAdapter(adapter);
		adapter.setOnItemClickListener(this);
		adapter.setOnItemChildClickListener(this);
		LinearSnapHelper pagerSnapHelper = new LinearSnapHelper();
		pagerSnapHelper.attachToRecyclerView(recycleView);
	}

	private void setPermissions() {
		rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
				.subscribe(new Consumer<Boolean>() {
					@Override
					public void accept(Boolean aBoolean) throws Exception {
						if (!aBoolean) {
							Toast.makeText(MainActivity.this,"为保证应用正常运行,请在权限管理开启必要权限!",Toast.LENGTH_SHORT)
									.show();
						}
					}
				});

	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 != -1) {
				switch (msg.what) {
					case REQUEST_UPHOTOS:
						smartRefresh.finishRefresh();
						smartRefresh.finishLoadMore();
						List<PhotosDTO> dtoList = mGson.fromJson(msg.obj.toString(), new TypeToken<List<PhotosDTO>>() {
						}.getType());
						adapter.addData(dtoList);
						break;
					default:
						break;
				}
			}
		}
	};

	private void getPhotos(int pages) {

		String page = String.valueOf(pages);
		mApi.getUPhotos(REQUEST_UPHOTOS,page);
	}

	@Override
	public void onItemClick(final BaseQuickAdapter adapter, View view, final int position) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			CardView cardView = (CardView)view.findViewById(R.id.item_card);
			ImageView imageView = (ImageView)view.findViewById(R.id.item_pic);
			ImageView profile = (ImageView)view.findViewById(R.id.item_profileImage);
			int width = cardView.getWidth();
			int height = cardView.getHeight();
			SPUtils.getInstance().put("width",width);
			SPUtils.getInstance().put("height",height);
			Pair<View, String> pairOne = new Pair<View, String>(imageView, "background");
			Pair<View, String> pairTwo = new Pair<View, String>(profile, "profile");
			startActivity(new Intent(MainActivity.this,PhotoDetailActivity.class)
					.putExtra("PId",((PhotosDTO)adapter.getData().get(position)).getId())
					.putExtra("ProfileImage",((PhotosDTO) adapter.getData().get(position)).getUser().getProfile_image().getLarge())
					.putExtra("Background",((PhotosDTO) adapter.getData().get(position)).getUrls().getRegular())
					.putExtra("UserName",((PhotosDTO) adapter.getData().get(position)).getUser().getName()),
					ActivityOptions.makeSceneTransitionAnimation(this,
							pairOne,pairTwo).toBundle());

		}else {
			startActivity(new Intent(MainActivity.this,PhotoDetailActivity.class)
					.putExtra("ProfileImage",((PhotosDTO) adapter.getData().get(position)).getUser().getProfile_image().getLarge())
					.putExtra("Background",((PhotosDTO) adapter.getData().get(position)).getUrls().getRegular())
					.putExtra("UserName",((PhotosDTO) adapter.getData().get(position)).getUser().getName()));
		}


	}


	@Override
	public void onLoadMore(RefreshLayout refreshLayout) {
		pages = pages + 1;
		getPhotos(pages);
	}

	@Override
	public void onRefresh(RefreshLayout refreshLayout) {
		pages = 1;
		adapter.setNewData(null);
		getPhotos(pages);
	}
	@Override
	public void onBackPressed() {
		long currentTime = System.currentTimeMillis();
		if (currentTime - lastBackTime < BACK_INTERVAL) {
			super.onBackPressed();
		} else {
			Toast.makeText(this, "Click again to exit", Toast.LENGTH_SHORT).show();
		}
		lastBackTime = currentTime;
	}

	@Override
	public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
		switch (view.getId()){
			case R.id.item_download:
				new QMUIDialog.MessageDialogBuilder(MainActivity.this)
						.setMessage("Download this picture?")
						.addAction("no", new QMUIDialogAction.ActionListener() {
							@Override
							public void onClick(QMUIDialog dialog, int index) {
								dialog.dismiss();
							}
						})
						.addAction("yes", new QMUIDialogAction.ActionListener() {
							@Override
							public void onClick(QMUIDialog dialog, int index) {
								String down_url = ((PhotosDTO) adapter.getData().get(position)).getLinks().getDownload();
								download(down_url);
								dialog.dismiss();
							}
						}).show();
				break;
			case R.id.item_profileImage:
				Toast.makeText(MainActivity.this,"Why fucking click me?",Toast.LENGTH_SHORT).show();
				break;
		}

	}


	// 保存图片到手机
	@SuppressLint("StaticFieldLeak")
	public void download(final String url) {

		new AsyncTask<Void, Integer, File>() {
			@Override
			protected void onPreExecute() {
				Toast.makeText(MainActivity.this,"Now Downloading",Toast.LENGTH_SHORT).show();
				super.onPreExecute();
			}

			@Override
			protected File doInBackground(Void... params) {
				File file = null;
				try {
					FutureTarget<File> future = Glide
							.with(MainActivity.this)
							.load(url)
							.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
					file = future.get();
					// 首先保存图片
					File pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
					File appDir = new File(pictureFolder ,"SPhoto");
					if (!appDir.exists()) {
						appDir.mkdirs();
					}
					String fileName = System.currentTimeMillis() + ".jpg";
					File destFile = new File(appDir, fileName);
					FileUtils.copy(file, destFile);
					// 最后通知图库更新
					sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
							Uri.fromFile(new File(destFile.getPath()))));
				} catch (Exception e) {
					Log.e("E", e.getMessage());
				}
				return file;
			}

			@Override
			protected void onPostExecute(File file) {
				Toast.makeText(MainActivity.this, "Saved in Pictures/SPhoto", Toast.LENGTH_SHORT).show();
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				super.onProgressUpdate(values);
			}
		}.execute();
	}
}
